import 'dart:async';
import 'dart:convert';
import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:native_dart_package/http/request/exception/api_exception.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/model/data_type_config.dart';
import 'package:yt_devops/model/device_model.dart';
import 'package:yt_devops/model/device_obj/group_config_model.dart';
import 'package:yt_devops/model/slave_ems_network_model.dart';
import 'package:yt_devops/pages/devices/device_list/device_list_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/base_detail_controller/base_detail_controller.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/battery_cell_tree/battery_cell_tree_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/device/device_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/device_es_group_view.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/dynamic_tabview.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/stastics_info_widget.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/device_base_info_widget/device_base_info_widget_view.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/new_air_cooling_page_model.dart';
import 'package:yt_devops/pages/devices/device_tab/model/device_item_model.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/socket/use_socket.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';
import 'component/battery_cluster.dart';
import 'component/charge_order_widget.dart';
import 'component/ev_charge_chart.dart';
import 'component/time_battery_info.dart';
import 'device_base_info_widget/device_base_info_widget_controller.dart';

class NewAirCoolingPageController extends BaseDetailController
    with GetTickerProviderStateMixin {
  NewAirCoolingPageModel newAirCoolingPageModel = NewAirCoolingPageModel();
  DeviceServices deviceServices = Get.find();
  DeviceModel? deviceModel;
  bool isInit = false; //是否初始化过
  /// 导航栏弹出层
  List<PopupMenuItem> actionList = [];

  ///渲染列表
  List<DeviceRealTimeModel> modelList = [];
  List<int> subDevicesIdList = []; //设备详情ems需要订阅的子设备
  List<String> subDevicesNameList = []; //设备详情ems需要订阅的子设备名称
  DeviceListModel? deviceTree;
  Map dataSource = {}; //旧的液冷需要去渲染的数据
  /// 从ems id列表
  List<int> salaveEmsIDs = [];

  /// 远程控制指令列表
  Map remotePage = {};

  /// 指令列表
  Map paramPage = {};

  /// 是否都单独一行展示
  bool isSingleLine = false;
  bool? isNew; //是否为新风冷和液冷
  /// 远程控制指令
  Map remoteControlMap = {};

  /// 配置信息
  Map configMap = {};

  ///是否包含电池模块单体信息
  bool isContainBattery = false;

  ///需要渲染的数据
  Map showMap = {};

  /// 页面顶部所有tab
  List<String> tabs = [];

  /// 页面所有tab对应的view
  List<Widget> tabviewList = [];

  ///需要订阅的物模型列表
  List<int> subscribeList = [];

  ///订阅从设备在线状态列表
  List<int> subscribeConnectStatusList = [];
  UseSubsribe subscribe = UseSubsribe(isContainDeviceId: true);
  UseSubsribe? connectStatusSubscribe;

  // Stream<Map<String, dynamic>>? dataStream;
  StreamController<Map<String, dynamic>>? streamController;

  ///电池组电池列表
  List<BatteryCellTreeModel> cells = [];
  BatteryCellTreeModel? batteryCellTreeModel;
  StreamSubscription<Map<String, dynamic>>? connectionSubscription;
  List tabviewMapList = [];
  TabController? tabController;

  ///基本信息控制器
  DeviceBaseInfoWidgetController baseInfoWidgetController =
      Get.put<DeviceBaseInfoWidgetController>(DeviceBaseInfoWidgetController());

  ///并网状态列表
  List<dynamic> gridMapDeviceList = [];

  ///并网状态需要订阅的设备
  List<int> gridDeviceList = [];

  ///是否隐藏电池模块的弹窗
  bool hiddenPop = false;

  /// 电池弹窗控制器
  BrnCloseWindowController closeController = BrnCloseWindowController();
  GetStorage storage = GetStorage();

  ///页面是否被加载过
  bool isLoading = false;

  ///如果列表需要展示tab,则需要去订阅tab里面的list的数据
  List<String> prefixList = [];

  bool get isSlave => deviceModel?.masterSlaveMode == MasterSlaveModeType.vice;

  @override
  void onInit() {
    super.onInit();
    _updateTabController();
  }

  @override
  void onReady() {}

  @override
  void onClose() async {
    Log.d('onClose===');
    await connectionSubscription?.cancel();
    await streamController?.close();
    await subscribe.closeListen();
    await connectStatusSubscribe?.closeListen();
    super.onClose();
  }

  TabController getTabController(int length) {
    return TabController(length: length, vsync: this);
  }

  Future toService(value) async {
    Get.back();
    if (value == 0) {
      await Get.toNamed(RouterPath.deviceControll, arguments: {
        'deviceId': deviceModel!.deviceId,
        'page': configMap,
        'title': ResKey.deviceParameterSetting.tr
      });
    } else if (value == 1) {
      /// 远程控制
      await Get.toNamed(RouterPath.deviceControll, arguments: {
        'deviceId': deviceModel!.deviceId,
        'page': remoteControlMap,
        'title': ResKey.remoteControll.tr
      });
    }
  }

  _updateTabView() {
    if (tabviewMapList.isNotEmpty) {
      for (var element in tabviewMapList) {
        Log.d('tabviewMapList===' + element.toString());
        tabviewList.add(DynamicTabView(element));
      }
    }
  }

  PopupMenuItem generatePopItem(Widget icon, String title, value) {
    return PopupMenuItem(
      value: value,
      enabled: false,
      key: GlobalKey(),
      child: Row(
        children: [
          icon,
          Gaps.hGap10,
          Text(
            title,
            style: TextStyles.f14,
          ),
        ],
      ),
    );
  }

  ///初始化数据
  initData(DeviceModel model) async {
    var map = storage.read('ossPhysicalModel${model.deviceId}');
    if (map != null) {
      _handleShowData(map);
    }
    getOssPhysicalModel(deviceModel!.productId!);
    isInit = true;
  }

  /// 获取物模型
  /// id = runningData 设备详情
  /// id =  config 参数设置
  /// id = remoteControl 远程控制,
  Future getOssPhysicalModel(int productId) async {
    actionList.clear();

    showLoading(toast: ResKey.loading.tr);
    var result = await deviceServices.getDeviceNewProperty(
        {'deviceId': deviceModel!.deviceId, 'platform': 1}, onError: (error) {
      dismissLoading();
      showError(error.message);
      return false;
    });
    dismissLoading();
    isLoading = true;
    if (result != null && result['data'] != null) {
      List list = result['data'];
      if (list.isEmpty) {
        update();
        return;
      }
      var isNewModel =
          list.indexWhere((element) => element['id'] == 'runningData') > -1;
      if (isNewModel) {
        for (var element in list) {
          if (element['id'] == 'runningData') {
            if (element != null) {
              showMap = element;
              // Log.d('showMap========' + showMap.toString());
              storage.write(
                  'ossPhysicalModel${deviceModel!.deviceId}', showMap);
            }
            _handleShowData(showMap);
          } else if (element['id'] == 'remoteControl' &&
              !FuncUtils.isListEmpty(element['children']) &&
              !isSlave) {
            //远程控制
            remoteControlMap = filterByAuthority(element) ?? {};
            var pass = remoteControlMap.keys.isNotEmpty;
            if (pass) {
              /// 没有权限，则不展示按钮

              actionList.add(generatePopItem(
                  Image.asset(
                    ImageAssets.iconRemoteControl,
                    fit: BoxFit.fill,
                  ),
                  ResKey.remoteControll.tr,
                  1));
            }
          } else if (element['id'] == 'config' &&
              !FuncUtils.isListEmpty(element['children']) &&
              !isSlave) {
            //参数配置
            configMap = filterByAuthority(element) ?? {};
            var pass = configMap.keys.isNotEmpty;
            if (pass) {
              /// 没有权限，则不展示按钮

              actionList.add(generatePopItem(
                  Image.asset(
                    ImageAssets.iconSetting,
                    fit: BoxFit.fill,
                  ),
                  ResKey.deviceParameterSetting.tr,
                  0));
            }
          }
        }
      } else {
        isNew = false;
        var properties = result['properties'];
        for (var element in properties) {
          element['type'] = 'group';
          element['name'] = element['groupName'];
          element['children'] = element['properties'];
          for (var child in element['children']) {
            child['type'] = properties;
          }
        }
        modelGroup({'children': properties});
      }
    }
    update();
  }

  ///处理需要动态展示的tab和tabview,如果是旧的液冷就展示一组一组的数据
  _handleShowData(Map map) {
    if (map['children'] != null) {
      List tempList = map['children'];
      if (tempList.first != null && tempList.first['children'] != null) {
        if (tempList.first['type'] == 'tab') {
          isNew = true;
          //按照tabbar样式渲染
          tabs.clear();
          tabviewList.clear();
          tabviewMapList.clear();
          tabs.add(ResKey.basicInformation.tr);
          prefixList.clear();
          tabviewList.add(DeviceBaseInfoWidgetPage(
            deviceModel: deviceModel,
            subDevicesIdList: subDevicesIdList,
            subDevicesNameList: subDevicesNameList,
            deviceTree: deviceTree,
          ));
          List tabList = tempList.first['children'];
          for (var element in tabList) {
            if (element['id'] != 'BmuTabs') {
              if (element['children'] != null &&
                  element['children'].isNotEmpty) {
                tabs.add(element['name'].toString());
              }
            } else {
              isContainBattery = true;
            }
            Log.d("当前测试内容 ==== $tabs");
            List childList = element['children'];
            Log.d('childList[0]====' + childList.toString());

            if (childList.isNotEmpty) {
              var tempTabList = [];
              for (var element in childList) {
                if (element['type'].toString() == 'tab') {
                  prefixList.add(element['id'].toString());
                }
                Log.d('prefixList====' + prefixList.toString());
                element['value'] = '--';
                if (element['id'].toString().contains('.')) {
                  element['id'] = element['id'].toString().split('.').last;
                }
                if (element['type'].toString() == 'property') {
                  if (element['deviceId'] != null) {
                    element['id'] = '${element['id']}-${element['deviceId']}';
                  } else {
                    element['id'] =
                        '${element['id']}-${deviceModel!.deviceId!}';
                  }
                }
                if (deviceModel != null &&
                    deviceModel!.productType ==
                        ProductType.newBatteryPack.value &&
                    element['id'].toString().contains('bmsOpenAndClose')) {
                  //针对电池的这个数据特殊处理下
                  element['id'] = element['id'].toString().replaceAll(
                      deviceModel!.deviceId!.toString(),
                      (deviceModel!.deviceId! - 2).toString());
                }
                if (element['deviceId'] != null &&
                    !subscribeList.contains(element['deviceId'])) {
                  subscribeList.add(element['deviceId']);
                }
                tempTabList.add(element);
              }
              Log.d('childList==' + childList.toString());
              if (childList[0]['dataInterceptor'] != 'request' &&
                  (childList[0]['type'].toString() == 'property' ||
                      childList[0]['type'].toString() == 'tab' ||
                      childList[0]['type'].toString() == 'group')) {
                if (childList[0]['type'].toString() == 'group') {
                  for (int i = 0; i < tempTabList.length; i++) {
                    var element = tempTabList[i];
                    if (i == 0) {
                      element['isExpand'] = '1';
                    } else {
                      element['isExpand'] = '0';
                    }
                  }
                }
                tabviewMapList.add(tempTabList);
                tabviewList.add(DynamicTabView(tempTabList));
              } else if (childList[0]['type'].toString() == 'component') {
                Log.d('component==' + childList[0]['id'].toString());
                switch (childList[0]['id']) {
                  case 'EVChargerChart':
                    //今日曲线
                    tabviewList.add(EvChargeChart(deviceModel!.deviceId));
                    break;
                  case 'EVChargerOrderInfo':
                    //订单信息
                    tabviewList.add(ChargeOrderWidget(deviceModel!.deviceId));
                    break;
                  case 'TimeBatteryInfo':

                    //充电桩统计
                    tabviewList.add(TimeBatteryInfo(
                      deviceModel!.deviceId!.toString(),
                    ));
                    break;
                  default:
                    tabviewList.add(Gaps.empty);
                }
              } else if (childList[0]['type'].toString() == 'group' &&
                  childList[0]['dataInterceptor'] == 'request') {
                tabviewList.add(StasticsInfoWidget(
                  deviceId: childList[0]['deviceId'],
                  apiUrl: childList[0]['id'],
                  modelList: childList[0]['children']
                      .map<StasticsInfoModel>((e) => StasticsInfoModel(
                          dataKey: e['id'],
                          dataName: e['name'],
                          dataType: e['dataType']))
                      .toList(),
                ));
              } else {
                if (element['id'] != null &&
                    element['id'].toString() != 'BmuTabs') {
                  Log.d('Container====' + prefixList.toString());
                  //排除电池模块
                  tabviewList.add(Container());
                }
              }
            } else {
              // tabviewList.add(Container());
            }
          }
          subscribe = UseSubsribe(isContainDeviceId: true);
          subscribeList.add(deviceModel!.deviceId!);
          streamController = subscribe.start(subscribeList, true);
          if (deviceModel != null &&
              deviceModel!.productType == ProductType.ems.value) {
            //如果是ems需要订阅从设备在线状态
            connectStatusSubscribe = UseSubsribe(isContainDeviceId: true);
          }
          if (deviceModel!.productType != ProductType.chargeGun.value) {
            // _updateTabView();
          }
          if (deviceModel?.masterSlaveMode != null &&
              deviceModel!.productType == ProductType.ems.value) {
            _getGridDeviceData();
          }
          if (isContainBattery &&
              deviceModel!.productType == ProductType.newBatteryPack.value) {
            getBatteryCell();
          }
          _updateTabController();

          ///数据加载完成并且是ems去订阅socket拉数据,不能提前订阅,不然第一次数据拿到了数据页面还没渲染出来
          ///如果设备离线,只要是设备上线过一次,连接上socket就有数据
          _steamListener();
          update();
        } else if (tempList.first['type'] == 'group') {
          isNew = false;
          streamController = subscribe.start([deviceModel!.deviceId!], true);
          //按照旧的液冷风格去渲染数据
          modelGroup(map);
        }
      }
    }
  }

  modelGroup(Map map) {
    modelList.clear();
    List<GroupConfigModel> groupList = [];
    groupList = List.generate(
        map['children'].length,
        (index) => GroupConfigModel.fromJson(map['children'][index])
          ..setChildren = map['children'][index]['children'] ?? []);

    /// 对设备详情的分组进行处理
    for (var group in groupList) {
      if (group.name == '接入设备列表') {
        /// 接入设备目前app不要求展示
        continue;
      }
      var properties = List.generate(
          group.children!.length,
          (index) => DetailItemModel(
              field: group.children![index]!['id'],
              label: group.children![index]['name'],
              format: (value) => FuncUtils.formatModelValue(
                  value,
                  DataTypeConfig.fromJson(
                      group.children![index]['dataType']))));
      modelList
          .add(DeviceRealTimeModel(groupName: group.name, items: properties));
      update();
    }
  }

  _handleChargeModuleGroup(List chargeModuleGroupList, String prefix) {
    if (chargeModuleGroupList.isEmpty) {
      return;
    }
    Map tempMap = {};
    for (int i = 0; i < chargeModuleGroupList.length; i++) {
      Map tempMaps = chargeModuleGroupList[i];
      tempMaps.forEach((key, value) {
        tempMap['$prefix[$i].$key'] = value;
      });
    }
    // Log.d('chargeModuleGroupList====' + chargeModuleGroupList.toString());
    // Map map = showMap;
    if (showMap['children'] != null) {
      List tempList = showMap['children'];
      if (tempList.first != null && tempList.first['children'] != null) {
        if (tempList.first['type'] == 'tab') {
          List tabList = tempList.first['children'];
          for (var element in tabList) {
            List childList = element['children'];
            if (childList.isNotEmpty) {
              for (var element in childList) {
                // Log.d('prefix===' + prefix.toString());
                // Log.d('prefix===' + deviceModel!.deviceId!.toString());

                if (element['type'].toString() == 'tab') {
                  // Log.d('element===' + element.toString());
                  if (element['id'].toString() == prefix) {
                    List childGroupList = element['children'];
                    if (childGroupList != null && childGroupList.isNotEmpty) {
                      for (var element in childGroupList) {
                        List tempList = element['children']?[0]?['children'];
                        if (tempList != null && tempList.isNotEmpty) {
                          for (var childElement in tempList) {
                            // Log.d('childElement===$childElement');
                            if (childElement['id'] != null &&
                                tempMap[childElement['id'].toString()] !=
                                    null) {
                              childElement['value'] =
                                  tempMap[childElement['id'].toString()]
                                      .toString();
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
          update();
        }
      }
    }
  }

  ///监听订阅的推送数据,刷新页面数据
  _steamListener() {
    if (isNew!) {
      streamController!.stream.listen((event) {
        // Log.d('prefixList====' + prefixList.toString());
        // Log.d('event====' + event.toString());

        if (prefixList.isNotEmpty) {
          for (var element in prefixList) {
            ///充电模块组
            if (event['$element-${deviceModel!.deviceId!}'] != null) {
              _handleChargeModuleGroup(
                  jsonDecode(
                      event['$element-${deviceModel!.deviceId!}'].toString()),
                  element);
            }
          }
        }
        for (var element in tabviewMapList) {
          List list = element;
          for (var subElement in list) {
            if (event[subElement['id'].toString()] != null) {
              subElement['value'] = event[subElement['id'].toString()];
            }
          }
        }
        baseInfoWidgetController.updateData(event);
        update();
        if (deviceModel!.productType == ProductType.ems.value &&
            gridMapDeviceList.isNotEmpty) {
          for (var element in gridMapDeviceList) {
            if (event[element[
                        '${element['systemWorkStatusId']}-${element['deviceId']}']
                    .toString()] !=
                null) {
              element['${element['systemWorkStatusId']}-${element['deviceId']}'] =
                  event[element[
                              '${element['systemWorkStatusId']}-${element['deviceId']}']
                          .toString()]
                      .toString();
            }
          }
          update();
        }
      });
    }
  }

  ///获取电池模块单体信息
  void getBatteryCell() async {
    var data = await deviceServices.getBatteryDevices({
      'deviceId': deviceModel!.deviceId,
    });
    cells = List.of(data).map((e) => BatteryCellTreeModel.fromMap(e)).toList();
    if (cells.isNotEmpty) {
      batteryCellTreeModel = cells.first;
    }
    tabs.add(ResKey.deviceBatteryModuleIndividualInformation.tr);
    BatteryCluster cluster = BatteryCluster(
      batteryCellTreeModel,
      deviceModel!,
      closeController,
      isShow: hiddenPop,
    );
    cluster.closeController;
    tabviewList.add(cluster);
    _updateTabController();
    update();
  }

  ///更新tabController,不然动态tab会有bug
  _updateTabController() {
    tabController = TabController(length: tabs.length, vsync: this);
    tabController!.addListener(() {
      closeController.closeMoreWindow();
      FocusScope.of(Get.context!).requestFocus(FocusNode());
    });
  }

  ///获取并网状态信息
  _getGridDeviceData() async {
    if (deviceModel?.deviceId == null) {
      return;
    }
    // showLoading(toast: ResKey.loading.tr);
    List? result = await deviceServices.getDeviceEsGroup({
      'deviceId': deviceModel!.deviceId,
    }, onError: (error) {
      dismissLoading();
      showError(error.message);
      return false;
    });
    dismissLoading();

    if (result != null && result!.isNotEmpty) {
      for (var element in result!) {
        if (element['systemWorkModelId'] != null) {
          element['${element['systemWorkModelId']}-${element['deviceId']}'] =
              '--';
        }
        if (element['systemWorkStatusId'] != null) {
          element['${element['systemWorkStatusId']}-${element['deviceId']}'] =
              '--';
        }
        if (element['deviceId'] != null) {
          gridDeviceList.add(element['deviceId']);
        }
        gridMapDeviceList.add(element);
      }
      tabs.add(ResKey.gridConnectStatus.tr);
      tabviewList.add(DeviceEsGroupView(gridMapDeviceList));
      _updateTabController();
      subscribeList.addAll(gridDeviceList);
      subscribeConnectStatusList.addAll(gridDeviceList);

      ///重新订阅物模型
      subscribe = UseSubsribe(isContainDeviceId: true);
      streamController = subscribe.start(subscribeList, true);
      baseInfoWidgetController.updateSubscribeList(gridDeviceList);

      ///重新订阅设备连接状态
      Future.delayed(const Duration(seconds: 1)).then((value) {
        connectStatusSubscribe = UseSubsribe(isContainDeviceId: true);
        connectionSubscription = connectStatusSubscribe
            ?.start(subscribeConnectStatusList, true,
                type: MessageEventType.networkStatus)
            .stream
            .listen((event) {
          // Log.d('从设备在线状态1111 $event');
          for (var element in gridMapDeviceList) {
            if (event[element['deviceId'].toString()] != null) {
              element['connectStatus'] = event[element['deviceId'].toString()];
            }
          }
          update();
        });
      });
      update();
    }
  }

  ///
  /// 获取物模型
  /// 订阅数据
  /// 如果是ems ， 则获取从ems列表，并订阅从ems在线状态
  ///
  init(DeviceModel model) async {
    subscribe = UseSubsribe(isContainDeviceId: false);
    Map? map = storage.read('ossPhysicalModel${model.deviceId}');
    if (map != null) {
      _handleShowData(map);
    }

    /// ems 都单独一行展示
    isSingleLine = model.productType == ProductType.ems.value;
    await getOssPhysicalModel(model.productId!);
    streamController = subscribe.start([model.deviceId!], true);
    if (model.productType == ProductType.ems.value) {
      getEmsDevices().then((value) {
        if (salaveEmsIDs.isEmpty) {
          return;
        }
        connectStatusSubscribe = UseSubsribe(isContainDeviceId: true);
        connectionSubscription = connectStatusSubscribe
            ?.start(salaveEmsIDs, true, type: MessageEventType.networkStatus)
            .stream
            .listen((event) {
          // Log.d('从设备在线状态 $event');
          streamController?.add(event);
        });
      });
    }
  }

  /// 获取从ems列表
  Future getEmsDevices() async {
    try {
      var data = await deviceServices.getEmsDeviceNet({
        'deviceId': deviceModel!.deviceId,
      });
      List<DetailItemModel> itemModels = [];
      for (var i = 0; i < data.length; i++) {
        var slaveEmsNetworkModel = SlaveEmsNetworkModel.fromJson(data[i]);
        salaveEmsIDs.add(slaveEmsNetworkModel.deviceId!);
        itemModels.add(DetailItemModel(
            label:
                '${slaveEmsNetworkModel.deviceName}${ResKey.fromEmsCommunicationStatus.tr}',
            field: 'networkStatus-${slaveEmsNetworkModel.deviceId}',
            format: (int? value) => $enumDecode(
                    $ConnectStatusTypeEnumMap, value,
                    unknownValue: ConnectStatusType.unConfig)
                .label));
      }
      if (itemModels.isNotEmpty) {
        modelList.add(DeviceRealTimeModel(
            groupName: ResKey.fromEmsList.tr, items: itemModels));
      }
      update();
    } on ApiException catch (e) {
      showError(e.message);
    }
  }

  /// 过滤掉没有“detail”权限的项
  Map? filterByAuthority(Map page) {
    if (FuncUtils.isPassTargetAuthority(page['authority'],
        permissionSource: UserEntityManager().webPermission)) {
      List children = page['children'] ?? [];
      List filtedChildren = [];
      for (var i = 0; i < children.length; i++) {
        var map = filterByAuthority(children[i]);
        if (map != null) {
          filtedChildren.add(map);
        }
      }
      if ((!FuncUtils.isListEmpty(children) &&
              FuncUtils.isListEmpty(filtedChildren)) ||
          FuncUtils.isListEmpty(children) && page['type'] != 'property') {
        /// 下级都没有权限，则移除父级
        return null;
      } else {
        page['children'] = filtedChildren;
      }

      return page;
    } else {
      return null;
    }
  }
}
